<style scoped>
  .clientReceive{
    margin-right: 0.5vw;
    padding: 0 15px;
    background-color: white;
    height: 95vh;
    position: relative;
  }
  .cog-top{
    display: flex;
    padding: 1.5vh 0;
    border-bottom: 2px solid #f4f4f4;
  }
  .cog-top p:first-child{
    margin: 3px 6px 0 0;
    display: inline-block;
    white-space:nowrap;
  }
  .cog-top p:not(:first-child){
    margin: 3px 6px 0 12px;
    display: inline-block;
    white-space:nowrap;
  }
  .top-inp{
    width: 160px;
  }
  .cog-btn{
    display: flex;
    justify-content: space-between;
    padding: 1.5vh 0;
  }
  .footView span{
    float: left;
    margin-right: 48px;
    line-height: 6vh;
    font-size: 14px;
  }
  .footView span i{
    margin-right: 5px;
  }
</style>

<style>
  .clientReceive .cog-top .el-input__inner{
    height: 30px;
  }
  .clientReceive .cog-btn .el-checkbox.is-bordered{
    padding: 5px 10px 0 10px;
    height: 30px;
  }
  .clientReceive .el-input__icon{
    line-height: 30px;
  }
  .clientReceive .el-button{
    margin: 0 10px 0 0;
  }
</style>

<template>
  <div class="clientReceive">
    <!-- 客户其他应收 -->
    <div class="cog-top">
        <p>应收日期</p>
        <el-date-picker
        class="top-inp"
          v-model="inputDate"
          type="date"
          placeholder="选择日期"
          value-format="yyyy-MM-dd">
        </el-date-picker>

        <p>客户</p>
        <el-input style="width:60px;margin-right:10px;" v-model="customerNo" @blur="customerNoBlur" :disabled="jxAgent"></el-input>
        <el-select :disabled="jxAgent"
          style="width:100px;"
          v-model="customerName" @change="e=>{this.customerNo=e}">
          <el-option
            v-for="item in customerList"
            :key="item.value"
            :label="item.label"
            :value="item.value">
            <span style="float:left">{{item.value}}</span>
            <span style="float:right">{{item.label}}</span>
          </el-option>
        </el-select>

        <p>单号</p>
        <el-input class="top-inp" v-model="receiptsNumber"></el-input>

        <p>金额</p>
        <el-input class="top-inp" v-model="money"></el-input>

        <p>备注</p>
        <el-input style="width:350px;" v-model="remark"></el-input>
    </div>

    <div class="cog-btn">
      <div>
      <el-button @click="save" type="primary" icon="el-icon-folder-checked">保存</el-button>
      <el-button @click="change" icon="el-icon-edit-outline">编辑</el-button>
      <el-button @click="printClick" icon="el-icon-printer">列印</el-button>
      <el-button @click="del" icon="el-icon-delete">删除</el-button>
      </div>
      <div>
        <span>应收序号：{{sequence}}</span>
      </div>
    </div>

    <el-table
      :header-cell-style="{background:'#f4f4f4',padding:0,height:'40px'}"
      :cell-style="{padding:0,height:'36px'}"
      :data="tableData"
      highlight-current-row
      style="width: 100%"
      height="75.5vh"
      @row-click="rowClick">
      <template v-for="i in this.Hlist">
        <el-table-column
          :key="i.prop"
          :prop="i.prop"
          :label="i.label"
          :width="i.width">
        </el-table-column>
      </template>
    </el-table>

    <foot-view class="footView">
      <div slot="text">
        <span>数据库：{{jxQuarter}}</span>
      </div>
    </foot-view>

    <div id="p" v-show=false></div>
  </div>
</template>

<script>
const resources = require('../../../config/printCSS6')

import footView from '../../../components/FootView'

import { getClient } from '../../../network/client'
import { list, insert, update, dele } from '../../../network/otherAccounts'
import { getSystemConfig } from '../../../network/operatoryCommand'

import today from '../../../components/mixins/today'
import enterUp from '../../../components/mixins/enterUp'

export default {
  name: 'client_receive',
  mixins: [today,enterUp],
  components:{
    footView
  },
  created(){
    let jxQuarterVal = document.cookie.match(RegExp('jxQuarter' + '=([^;]+)'))
    let jxAgentVal = document.cookie.match(RegExp('jxAgent'+'=([^;]+)'))
    let operatorVal = document.cookie.match(RegExp('jxAgent'+'=([^;]+)'))
    this.jxQuarter = jxQuarterVal ? jxQuarterVal[1] : null
    this.operator = operatorVal ? operatorVal[1] : null
   if(jxAgentVal){
    this.jxAgent = jxAgentVal[1] == 1 ? true : false
   }
    
    this.inpList = this.getInput()
    // 随机数赋值
    this.pageSession = Math.ceil(Math.random()*1000000)+''

    // 获取所有客户信息
    getClient({limit:99999}).then(res => {
      // // console.log(res)
      if (res.data.code == 200) {
        let list = res.data.data
        list.forEach(e => {
          if(e.stop != 1){
            this.customerList.push({value:e.no,label:e.name,contact:e.contact,address:e.address,phone:e.phone,cellphone:e.cellphone})
          }
        })
        if (this.jxAgent) {
          for (const i of this.customerList) {
            if (i.label == this.operator) {
              this.customerNo = i.value
              this.customerName = i.value
              break
            }
          }
        }
      }
    })

    getSystemConfig().then(res => {
      // console.log(res)
      if (res.data.data) {
        this.companyName = res.data.data.companyName
        this.companyPhone = res.data.data.phone
      }
    })
  },
  data(){
    return{
      inpList: [],
      pageSession: '',

      inputDate: this.searchDate(),
      customerNo: '',
      customerName: '',
      customerList: [],
      receiptsNumber: '',
      money: '',
      remark: '',
      sequence: '',
      
      tableData: [],
      Hlist: [
        {prop:'accountsSequence',label:'应收序号',width:''},
        {prop:'receiptsNumber',label:'单号',width:''},
        {prop:'customerNo',label:'客户编号',width:''},
        {prop:'money',label:'金额',width:''},
        {prop:'accountsTime',label:'应收日期',width:''},
        {prop:'remark',label:'备注',width:''}
      ],

      selectRow: null,
      jxQuarter: null,
      jxAgent:null,
      operator:null,
      // jxQuarter: document.cookie.match(RegExp('jxQuarter'+'=([^;]+)'))[1],
      // jxAgent: document.cookie.match(RegExp('jxAgent'+'=([^;]+)'))[1] == 1 ? true : false,
      // operator: document.cookie.match(RegExp('jxUser'+'=([^;]+)'))[1],

      companyName: '',
      companyPhone: '',
      today: this.searchDate()
    }
  },
  watch: {
    customerNo(a,b){
      this.customerNo = a.toUpperCase().trim()
    },
    receiptsNumber(a,b){
      this.receiptsNumber = a.toUpperCase().trim()
    }
  },
  methods:{
    save(){
      let d = {
        customerNo: this.customerNo,
        receiptsNumber: this.receiptsNumber,
        money: this.money,
        remark: this.remark,
        accountsTime: this.inputDate.slice(0,10)
      }
      insert(JSON.stringify(d)).then(res => {
        // console.log(res)
        if (res.data.code == 200) {
          this.$message({
            message: '保存成功',
            type: 'success'
          })
          this.sequence = res.data.data
          list({accountsSequence: this.sequence}).then(r => {
            // console.log(r)
            r.data.data.forEach(e => {
              e.accountsTime = e.accountsTime.slice(0,10)
              this.tableData.push(e)
            })
          })
        } else {
          this.$message.error('保存失败')
        }
      })
    },
    change(){
      if (this.tableData.length == 1) {
        this.selectRow = this.tableData[0]
      }
      if (!this.selectRow) {
        this.$message.info('请先选择一条数据再进行编辑')
        return
      }
      this.selectRow.accountsTime = this.inputDate.slice(0,10)
      this.selectRow.customerNo = this.customerNo
      this.selectRow.receiptsNumber = this.receiptsNumber
      this.selectRow.money = this.money
      this.selectRow.remark = this.remark

      update(JSON.stringify(this.selectRow)).then(res => {
        // console.log(res)
        if (res.data.code == 200) {
          this.$message({
            message: '修改成功',
            type: 'success'
          })
        } else {
          this.$message.error('修改失败')
        }
      })
    },
    del(){
      if (!this.sequence) return
      dele({sequence: this.sequence}).then(res => {
        // console.log(res)
        if (res.data.code == 200) {
          this.$message({
            message: '删除成功',
            type: 'success'
          })
          this.sequence = ''
          this.tableData = []
        } else {
          this.$message.error('删除失败')
        }
      })
    },

    rowClick(row){
      this.sequence = row.accountsSequence
      this.inputDate = row.accountsTime.slice(0,10) + ' 12:00:00'
      this.customerNo = row.customerNo
      this.receiptsNumber = row.receiptsNumber
      this.money = row.money
      this.remark = row.remark
      this.selectRow = row
      this.customerNoBlur()
    },

    // 客户编号失去焦点
    customerNoBlur(){
      if (this.customerNo != '') {
        for (const i of this.customerList) {
          if (this.customerNo == i.value) {
            this.customerName = i.label
            return
          }
        }
        this.$alert('无此客户编号', '', {
          confirmButtonText: '确定'
        })
        this.customerNo = ''
        this.customerName = ''
      } else {
        this.customerName = ''
      }
    },

    printClick(){
      if (!this.tableData.length) return
      document.getElementById('p').innerHTML = ''
      this.openPrint()
    },
    openPrint(n=0){
      let contact = ''
      let phone = ''
      let cellphone = ''
      let address = ''

      if (this.customerNo) {
        for (const i of this.customerList) {
          if (i.value == this.customerNo) {
            contact = i.contact
            phone = i.phone
            cellphone = i.cellphone
            address = i.address
          }
        }
      }

      const length = this.tableData.length
      let index = n
      let printBody = document.getElementById('p')
      let printHead = document.createElement('div')
      printHead.innerHTML = `
        <span class="printHead">
          ${this.companyName}${this.jxQuarter}客户应收单
        </span>
        <div class="info" style="border-top: 1px dashed black;">
          <p>客户：${this.customerNo}</p>
          <p>联系人：${contact}</p>
          <p>电话：${phone}</p>
          <p>打印日期：${this.today}</p>
        </div>
        <div class="info" style="border-bottom: 1px dashed black;">
          <p>客户地址：${address}</p>
        </div>
      `
      printHead.style.pageBreakBefore = 'always'
      printHead.style.paddingTop = '5mm'
      printBody.appendChild(printHead)

      let printTable = document.createElement('table')
      printTable.innerHTML = `
        <tr>
          <td width='4%'>序号</td>
          <td width='10%'>应收序号</td>
          <td width='12%'>单号</td>
          <td width='8%'>客户编号</td>
          <td width='10%'>金额</td>
          <td width='10%'>应收日期</td>
          <td>备注</td>
        </tr>
      `
      let row = null
      for (index; index < length; index++) {
        const e = this.tableData[index]
        row = printTable.insertRow(printTable.FetchRowCount)
        row.insertCell(0).innerHTML = index + 1
        row.insertCell(1).innerHTML = e.accountsSequence
        row.insertCell(2).innerHTML = e.receiptsNumber
        row.insertCell(3).innerHTML = e.customerNo
        row.insertCell(4).innerHTML = e.money
        row.insertCell(5).innerHTML = e.accountsTime
        row.insertCell(6).innerHTML = e.remark

        if (parseInt((index+1)/36) && (index+1)%36 == 0 && (index+1) != length) {
          printBody.appendChild(printTable)
          this.openPrint(index+1)
          return
        }
        if ((index+1) == length) {
          // 最后一条
          let lastItem = length%36
          if (!lastItem || lastItem > 33) {
            printBody.appendChild(printTable)
            this.openPrint(index+1)
            return
          }
        }
      }
      row = printTable.insertRow(printTable.FetchRowCount)
      row.insertCell(0).innerHTML = '合计'
      row.insertCell(1).innerHTML = ''
      row.insertCell(2).innerHTML = ''
      row.insertCell(3).innerHTML = ''
      row.insertCell(4).innerHTML = this.tableData[0].money
      row.insertCell(5).innerHTML = ''
      row.insertCell(6).innerHTML = ''
      printBody.appendChild(printTable)

      let printFoot = document.createElement('div')
      printFoot.innerHTML = `
        <div class="info" style="padding-right: 35mm;">
          <p>电话：${this.companyPhone}</p>
          <p>主管：</p>
          <p>财务：</p>
          <p>复核:</p>
        </div>
      `
      printBody.appendChild(printFoot)

      let printHtml = document.getElementById('p').innerHTML
      let wind = window.open("",'newwindow', 'height=500, width=1000, top=100, left=100, toolbar=no, menubar=no, scrollbars=no, resizable=no,location=no, status=no')
      wind.document.body.innerHTML = printHtml
      let style = document.createElement('style')
      style.type = 'text/css'
      style.innerHTML = resources.printCSS
      wind.document.head.appendChild(style)
      wind.print()
    }
  }
}
</script>